﻿using DeHeng_Mes.Dao.PlcDao;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Model.ConfigModel;
using DeHeng_Mes.Model.Singleton;
using DeHeng_Mes.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DeHeng_Mes.Model.Table;
using NPOI.SS.Formula.Functions;
using S7.Net;
using DeHeng_Mes.Model;
using System.Windows.Forms;
using System.Windows.Media;
using NPOI.HSSF.Record;

namespace DeHeng_Mes.Thread
{
    public class PowerGather
    {
        PlcDao plcDao = new PlcDao();
        PowerDao powerDao = new PowerDao();
       

        ProductionPowerDao productionPowerDao = new ProductionPowerDao();
        public async Task GetHourPower()
        {
            Tools.ProduceLogText("启动小时能耗采集");


            while (true)
            {
                try
                {
                    DateTime now = DateTime.Now;

                    int minute = now.Minute;

                    int second = now.Second;

                    if (minute == 0 && second == 0)
                    {
                        PlcOrderConfigModelList.ReadPlcList.ForEach(x => PowerCollection(x, now));
                    }

                    await Task.Delay(1000);
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogText("小时能耗采集失败，原因是" + ex.Message); ;
                }
            }

        }

    

        /// <summary>
        /// 能耗采集
        /// </summary>
        /// <param name="x"></param>
        private void PowerCollection(PlcOrderConfigModel orderModel, DateTime now)
        {
            try
            {
                // 获取实例字典
                Dictionary<object, Type> dictionary = MappingTable.PlcMapping(orderModel.plc, orderModel.PlcName);

                // 获取当前能耗
                string power = plcDao.GetStringFieldValue(dictionary, "Power", "RealTimePower");

                TraceHourPower traceHourPower = new TraceHourPower();

                traceHourPower.HourPower = power;
                traceHourPower.Hour = now.Hour.ToString();
                traceHourPower.PlcName = orderModel.PlcName;
                traceHourPower.Date = now;
                PowerDao.insertPower(traceHourPower);
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"{orderModel.PlcName}插入数据库失败，原因是{ex.Message}");
            }


        }
    }
}
